#!/bin/bash

# 提示用户输入域名
read -p "请输入域名（例如：example.com）: " DOMAIN

# 验证域名格式（基本检查）
if ! [[ $DOMAIN =~ ^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
    echo "错误：域名格式无效"
    exit 1
fi

# 提示用户输入IP地址
read -p "请输入IP地址（例如：192.168.0.55）: " IP

# 验证IP地址格式（基本检查）
if ! [[ $IP =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    echo "错误：IP地址格式无效"
    exit 1
fi

# 使用提供的域名和IP生成YAML文件
cat << EOF > coredns-configmap.yaml
apiVersion: v1
data:
  Corefile: |
    .:53 {
        errors
        health {
           lameduck 5s
        }
        ready
        template IN A $DOMAIN {
          match .*.$DOMAIN
          answer "{{ .Name }} 60 IN A $IP"
          fallthrough
        }
        kubernetes cluster.local in-addr.arpa ip6.arpa {
           pods insecure
           fallthrough in-addr.arpa ip6.arpa
           ttl 30
        }
        prometheus :9153
        forward . /etc/resolv.conf {
           max_concurrent 1000
        }
        cache 30
        loop
        reload
        loadbalance
    }
  local-zone.db: |
    *.$DOMAIN IN A $IP
kind: ConfigMap
metadata:
  name: coredns
  namespace: kube-system
EOF

# 输出生成文件的信息
echo "已生成 coredns-configmap.yaml，域名=$DOMAIN，IP=$IP"

# 将YAML文件应用到Kubernetes
kubectl apply -f coredns-configmap.yaml

# 检查应用是否成功
if [ $? -eq 0 ]; then
    echo "成功应用 CoreDNS ConfigMap"
    kubectl rollout restart deployment coredns -n kube-system
else
    echo "应用 CoreDNS ConfigMap 失败"
    exit 1
fi